<?php
require_once('config.inc.php');
require_once('DatabaseManager.php');

$db = new DatabaseManager;
$db -> createDB();

$dbname = DB_NAME;

if(!@$title = $_POST["title"])
  $title = '';
if(!@$first_name = $_POST["first_name"])
  $first_name = '';
if(!@$last_name = $_POST["last_name"])
  $last_name = '';
if(!@$postcode = $_POST["postcode"])
  $postcode = '';
if(!@$city = $_POST["city"])
  $city = '';
if(!@$country = $_POST["country"])
  $country = '';
if(!@$address = $_POST["address"])
  $address = '';
if(!@$phone = $_POST["phone"])
  $phone = '';
if(!@$position = $_POST["position"])
  $position = '';
if(!@$employer = $_POST["employer"])
  $employer = '';
if(!@$mail = $_POST["mail"])
  $mail = '';
if(!@$homepage = $_POST["homepage"])
  $homepage = '';

/* make connection to database */
MYSQL_CONNECT(DB_SERVER,DB_USER_NAME,DB_USER_PASSWORD) OR DIE("Could not connect to Database!");
@mysql_select_db("$dbname") or die("Database not found!"); 

class InsertUserData
{
  function insertData($first_name, $last_name, $address, $postcode, $city, $country, $phone, $employer, $mail, $title, $homepage, $position)
  {
		/* MySQL table created to store the data */
		$tablename = "userdata";
	
		$query1 = "SELECT * FROM $tablename WHERE firstname = '$first_name' AND lastname = '$last_name'";
		$result1 = MYSQL_QUERY($query1);
		$num_rows =  mysql_num_rows($result1);
			
		if(!$num_rows)
		{
		  /* Insert information into table */
		  $query2 = "INSERT INTO $tablename VALUES('NULL', '$first_name', '$last_name', '$address', $postcode, '$city', '$country', '$phone', '$employer', '$mail', '$title', '$homepage', '$position')";
		  $result2 = MYSQL_QUERY($query2);
			
		  if($result2)
		  {
				$affected_rows =  mysql_affected_rows();
				$this->createUserDirectories(mysql_insert_id());
		  }
		  else
		    include("errorpage.php");
		}
		else
	    include("errorpage.php");
  }
	
  function createUserDirectories($user_id)
  {
		if (!file_exists(dirname(__FILE__)."/../users/"))
		mkdir (dirname(__FILE__)."/../users/");
		            
		mkdir(dirname(__FILE__)."/../users/".$user_id);
		mkdir(dirname(__FILE__)."/../users/".$user_id."/home");
		mkdir(dirname(__FILE__)."/../users/".$user_id."/templates");
		mkdir(dirname(__FILE__)."/../users/".$user_id."/templates/1");
		mkdir(dirname(__FILE__)."/../users/".$user_id."/templates/2");
		mkdir(dirname(__FILE__)."/../users/".$user_id."/templates/3");
  }	
}

$userdata = new InsertUserData();
$userdata->insertData($first_name, $last_name, $address, $postcode, $city, $country, $phone, $employer, $mail, $title, $homepage, $position);

include("index.php");

/* Close the database connection */
MYSQL_CLOSE();
?>